//成品新增和编辑页面

var RATE=Number($.cookie("RingRate")) || 1;
var EDITMODE=false;
var xhrVideo = new XMLHttpRequest();
(function(){
	var addForm={
		init:function(){
			myApp.showIndicator();
			this.bindEvents();
			this.loadCommon();
			myApp.hideIndicator();
		},
		bindEvents:function(){
			var self=this;
			$("#rate").text(RATE);
			//编辑
			args = GetUrlParms();				
			if(args["ID"]!=undefined){						
				ID = args["ID"];//产品ID		
				EDITMODE=true;
			}
			if(EDITMODE){
				$(".category").hide();
				self.bindData(ID);
				$("#page_title").html(_("成品编辑"));
			}else{
				$('.category').show();
				$("#page_title").html(_("成品新增"));
			}
			//修改新增：采购人
            var html_purchaseAgent = "";
            if (list.msgcode ==true) {
                for(var k in list.msginfo){
                    html_purchaseAgent +='<option value="'+k+'">'+ _(list.msginfo[k]) +'</option>';
                }
            }
            else {
                html_purchaseAgent += "<option></option>";
            }
            $("#purchaseAgent").append(html_purchaseAgent);
			//切换主石类型
			//self.changType(1);
			//self.sizeParams(1);
			$("#data_category").on("click","span",function(){
				$(this).addClass("active").siblings().removeClass("active");
				var type=$("#data_category span.active").attr("data-value");				
				self.changType(type);
			});
			//关闭弹框
			$("#close_tip_btn").on("click",function(){
				$("#tip_box").hide();
			});
			//美金与人民币的转换
			$("#usd_input").bind('input propertychange', function() {
				var usdVal=$(this).val();				
//				if(usdVal*RATE>= 1000000000){
//					$("#tip_box").show();
//					$("#tip_content").html("请输入正确的价格！");
//				}
				$("#rmb_input").val(formatRMBPrice(usdVal*RATE));
			});
			$("#rmb_input").bind('input propertychange', function() {
				var rmbVal=$(this).val();
//				if(rmbVal>= 1000000000){
//					$("#tip_box").show();
//					$("#tip_content").html("请输入正确的价格！");
//				}
				$("#usd_input").val(formatUSDPrice(rmbVal/RATE));
			});

			//采购价格美金和人民币的转换
			$("#purchaseUSDPerGrain").bind('input propertychange', function() {
				var usdVal=$(this).val();
                var purchaseRate=$("#purchaseExchange").val();
				$("#purchaseRMB").val(formatRMBPrice(usdVal*purchaseRate));
			})

            $("#purchaseRMB").bind('input propertychange', function() {
                var rmbVal=$(this).val();
                var purchaseRate=$("#purchaseExchange").val();
                $("#purchaseUSDPerGrain").val(formatUSDPrice(rmbVal/purchaseRate));
            })
            //通过采购汇率计算
            $("#purchaseExchange").bind('input propertychange',function(){
                var purchaseRate=$(this).val();
                var usdVal=$("#purchaseUSDPerGrain").val();
                if(usdVal && purchaseRate){
                	$("#purchaseRMB").val(formatRMBPrice(usdVal*purchaseRate));
				}
				var rmbVal=$("#purchaseRMB").val();
                if(rmbVal && purchaseRate){
                	$("#purchaseUSDPerGrain").val(formatUSDPrice(rmbVal/purchaseRate));
				}

            })


			//提交验证
			$("#submit_btn").on("click",function(){
				$("#form_data").submit();
			});
			$("#reset_btn").on("click",function(){
				if(EDITMODE){
					myApp.alert(_("编辑时不能重置参数！"));
				}else{
					$("#form_data")[0].reset(); 
				}				
			});
            var aValidate = $("#form_data").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                	if($("#SideWeight").val()==""){
                		$("#SideWeight").val(0);
                	}
                	 //self.addProduct();
					var StyleNo=$("#styleNo").val();
                	self.unImg(StyleNo);
                },
                rules: {
                    OriginSN: "required",
                    MainShape: "required",
                    MainWeight: "required",
                    Weight: "required",
					// State: "required",
					StyleNo: "required",
                    Price: {
					    required: true,
					    max: 1000000000
					  },
                    Series: "required",
                },
                messages: {
                    OriginSN: "",
                    MainShape: "",
                    MainWeight: "",
                    Weight: "",
					// State:"",
					StyleNo: "",
                    Price: {
                    	required:"",
					    max: _("价格必须小于9位数")
					  }, 
                    Series: "",                    
                }
            });
			
		},
		//编辑时绑定数据
		bindData:function(ID){
			$("#form_reset_btn").attr("disabled", true);
			myApp.showIndicator();//显示加载中
			var self=this;
			var submitJson={};
			submitJson.ID=ID;
			submitJson.GoodsType=3;
			if(EDITMODE){
				submitJson.IsMyStock=true;
			}
			$.ajax({
				url:'/Team/GetProductData',
				type:'POST',
				data: JSON.stringify(submitJson),
				dataType:'JSON',
				contentType: "application/json; charset=utf8",
				success:function(result){
					var res=eval('(' + result + ')')
					if(res.msgcode==true){
						var datas=res.msginfo.rows;	
						var data =datas[0];	
						self.changType(data.Category);					
						$("#data_category").find("span").eq(data.Category-1).addClass("active").siblings().removeClass("active");//类型的绑定
						$("#form_data").setForm(data);//帮数据
						$("#usd_input").val(formatUSDPrice((data.Price)/RATE));
						$("#id_input").prop({"name":"ID","value":data.ID});//ID

                        if(data.ShipTime){
                            $("#data_ShipTime").val($.trim(YearDateFormats(data.ShipTime)));
                        }
                        if(data.PurchaseTime){
                            $("#data_PurchaseTime").val($.trim(YearDateFormats(data.PurchaseTime)));//-买入时间
                        }
                        if(data.ArrivalTime){
                            $("#data_ArrivalTime").val($.trim(YearDateFormats(data.ArrivalTime)));//到货时间
                        }
						//推荐
						$("#form_Tag").val(data.Tag);
                        //视频绑定
                        if(data.Videos!=''){
                            var _CRE_FILE = document.createElement("input");
                            _CRE_FILE.setAttribute("type", "file");
                            _CRE_FILE.setAttribute("class", "video_file");
                            _CRE_FILE.setAttribute("id", "video_input");
                            _CRE_FILE.setAttribute("style", "display:none");
                            _CRE_FILE.setAttribute("data-url",data.Videos );
                            $('.video_one').after(_CRE_FILE);
                            var videoHtml= '<section class="up-section fl close_f" style="margin-left: 5px; position: relative;width: 136px;height: 136px">'+
                                '<img src="/images/a7.png" class="close-upimg" onclick="closeVideo()" style="display: block">'+
                                '<embed src="'+data.Videos+'" style="width: 100%;height: 100%;display: block;">'+
                                '</section>';
                            $('.video_one').after(videoHtml)
                        }


                        //图片的绑定
						if(data.Images!=""){
							imgs = data.Images.split("|");
							 for (var i=0; i< imgs.length;i++) {
							 	var img_boxHmtl=[
					    			'<section class="up-section fl load">',
										'<span class="up-span"></span>',
										'<img src="/images/a7.png" class="close-upimg"  style="display: block;top:4px;right:2px;width:16px;height:16px">',
										'<img src=',imgs[i],' class="up-img" data-src=',imgs[i],'>',
										'<p class="img-namep"></p>',
										'<input id="taglocation" name="taglocation" value="" type="hidden">',
										'<input id="tags" name="tags" value="" type="hidden">',
									'</section>'
					    		].join('');
					    		$("#img_box").append(img_boxHmtl);
							 }
						}
					}else{
						myApp.alert(_("加载失败！"));
					}
					myApp.hideIndicator();//隐藏加载中
				}
			});
		},
         dataURLtoBlob:function(dataurl) {
			var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
			while(n--){
				u8arr[n] = bstr.charCodeAt(n);
			}
			return new Blob([u8arr], {type:mime});
		},
		unImg:function(StyleNo) {
			var isImg=false;
			var self=this;
			var len=$('.up-img').length;
			var formData=new FormData();
             for (var i=0;i<len;i++){
                 var dataSrc=$('.up-img').eq(i).attr('data-src');
                 if(dataSrc.indexOf('http://')==-1){
					 isImg=true;
                     var blob= self.dataURLtoBlob(dataSrc);
                     formData.append("image", blob, "image" + i + ".png");
                 }

             }
			args = GetUrlParms();
			if(args["type"]!=undefined){
				TYPE = args["type"];//产品类型
			}

			myApp.showIndicator();
			if(!isImg){
				if($('.video_file').length>0){
					self.HandVideoStr(StyleNo)
				}else {
					self.addProduct();
				}
				return false;
			}
			var upload_img_url;
			if(EDITMODE == true){
				upload_img_url="/team/UploadImages?type=inlays&styleNo="+StyleNo;
			}else{
				upload_img_url="/team/UploadImage?type=inlays";
			}

			$.ajax({
				url: upload_img_url,
				data: formData,
				type: 'POST',
				cache: false,
				processData: false,
				contentType: false,
				dataType: 'JSON',
				success: function(result) {
					var _result=eval('('+result+')');
					if(_result.result==true){
                        var len=$('.up-img').length;
                        for(var i = 0; i < _result.successes.length; i++) {
                            $('.new_up').eq(i).attr('data-src', _result.successes[i][1]);
                        }
					}
                    if($('.video_file').length>0){
                        self.HandVideoStr(StyleNo)
                    }else {
                        self.addProduct();
                    }
				},
				error:function(XMLHttpRequest, textStatus, errorThrown){
					myApp.alert(XMLHttpRequest.responseText);
				}

			});
		},

        //上传视频 start
        HandVideoStr:function(StyleNo) {
			myApp.showIndicator();
            var self=this;
            var fd = new FormData();
            var _this=document.getElementById("video_input");

            if($('#video_input').attr('data-url')){
                self.addProduct($('#video_input').attr('data-url'))
            }else {
                fd.append("fileToUpload", _this.files[0]);
                xhrVideo.onreadystatechange = function() {
                    self.videoFun();
                };
                if(EDITMODE == true){
                	xhrVideo.open("post", 'UploadVideos?type=inlays&styleNo='+StyleNo, true);
				}else{
                	xhrVideo.open("post", 'UploadVideo?type=inlays', true);
				}
                xhrVideo.send(fd);
            }

        },
        videoFun:function() {
            var self=this;
            var mp4Data='';

            if(xhrVideo.readyState == 4 && xhrVideo.status == 200) {
                var obj = $.parseJSON(xhrVideo.responseText);
                var _result = eval('(' + obj + ')'); //eval()解析单个json对象
                if(_result.msgcode == false) {
                    myApp.alert(_result.msginfo);
                } else {
                    if(_result.result==false){
                        self.addProduct(mp4Data)
                    }else {

                        mp4Data=_result.successes[0][1];
                        self.addProduct(mp4Data)
                    }
                }
            }
        },
        //上传视频end

		//新增提交
		addProduct:function(mp4Data){
			//图片链接
			var images=[];
			var img_sectionLength=$(".img-section").find("section.up-section").length;
			if(img_sectionLength==0){
				myApp.alert(_("请上传图片"));
				myApp.hideIndicator();//隐藏加载中
			}else{
				 myApp.showPreloader(_("上传中，请稍等!"));
				//获取图片地址
				for(var i=0;i<img_sectionLength;i++){
					var img_li=$(".img-section").find("section.up-section").eq(i);
					var img_src=img_li.find(".up-img").attr("data-src");
					images.push(img_src);
				}
                var imgs=images.join('|');//拼成字符串
	    		$("#Images").val(imgs);//图片
	    		$("#Category").val($("#data_category span.active").attr("data-value"));
				// var params = $("#form_data").serializeArray();
			    var finalRes = $('#form_data').serializeArray().reduce(function(result, item){
		             result[item.name] = item.value;
		            return result;
		        }, {})//把提交的数据转为JSON格式
				finalRes.Tag=$("#form_Tag").val();
		        if(EDITMODE){
					finalRes.GoodsType=3;
		        	var manageURL="/Team/ModifyProductData";
		        }else{
					finalRes.GoodsType=3;
		        	var manageURL="/Team/AddProductData";
		        }
                finalRes.Videos=mp4Data||'';//视频
				 $.ajax({
				 	type:"POST",
				 	url:manageURL,
				 	data:JSON.stringify(finalRes),
				 	contentType: "application/json; charset=utf-8",
	                success: function (result) {
	                	var _result = eval('(' + result + ')');//eval()解析单个json对象
	                     myApp.hidePreloader();
	                	if(EDITMODE){
							var tipString=_("修改");
	                	}else{
	                		var tipString=_("新增");
	                	}
	                	if(_result.result==true){
	                		myApp.alert(tipString+_("成功！"));
	                	}else{
	                		myApp.alert(tipString+_("失败！"));
	                	}
						myApp.hideIndicator();//隐藏加载中
	                }
				 });
			}
			
		},
		
		//公共参数
		loadCommon:function(){
			//主石
			var category='';
			category+='<span style="display:none"   data-value="">空托</span>'+
				'<span class="active"  data-value="2">白钻</span>'+
				'<span  data-value="3">彩钻</span>'+
				'<span  data-value="4">红宝</span>'+
				'<span   data-value="5">蓝宝</span>'+
				'<span   data-value="6">祖母绿</span>'+
				'<span  data-value="7">坦桑</span>'+
				'<span   data-value="8">碧玺</span>';
			
			$("#data_category").html(category);//主石类型
			//类型
			var type='';
			for (var i = 0; i < inlay[1].Type.length; i++) {
				type +='<option value="'+inlay[1].Type[i][0]+'">'+ _(inlay[1].Type[i][1]) +'</option>';
			}
			$("#data_type").html(type);
			//形状
			var shape='';
			for (var i = 0; i < inlay[1].MainShape.length; i++) {
				shape +='<option value="'+inlay[1].MainShape[i][0]+'">'+ _(inlay[1].MainShape[i][1]) +'</option>';
			}
			$("#data_shape").html(shape);
			//材质
			var material='';
			for (var i = 0; i < inlay[1].Material.length; i++) {
				material +='<option value="'+inlay[1].Material[i][0]+'">'+ _(inlay[1].Material[i][1]) +'</option>';
			}
			$("#data_material").html(material);
			//风格
			var data_style='';
			for (var i = 0; i < inlay[1].Style.length; i++) {
				data_style +='<option value="'+inlay[1].Style[i][0]+'">'+ _(inlay[1].Style[i][1]) +'</option>';
			}
			$("#data_style").html(data_style);
			//所在地国家
			var country='';
			for (var i = 0; i < inlay[1].Country.length; i++) {
				country +='<option value="'+inlay[1].Country[i][0]+'">'+ _(inlay[1].Country[i][1]) +'</option>';
			}
			$("#data_country").html(country);
			// //状态
			var status='';
			for(var i=0;i<inlay[1].Status.length;i++){
				status+='<option value="'+inlay[1].Status[i][0]+'">'+_(inlay[1].Status[i][1])+'</option>';
			}
			$("#data_status").html(status);
			var receiptStatus='';
			for(var i=0;i<inlay[1].ReceiptStatus.length;i++){
				receiptStatus+='<option value="'+inlay[1].ReceiptStatus[i][0]+'">'+_(inlay[1].ReceiptStatus[i][1])+'</option>';
			}
			$("#data_receiptStatus").html(receiptStatus);
		},
		// 切换类型
		changType:function(type){
			$("#data_color,#data_clarity,.data_cert,#data_place,#data_process").remove();
			if(type && type>1){
				//颜色
				var color='<div class="form_control" id="data_color"><label><b class="no_null">*</b>'+_("颜色")+'：</label><select name="MainColor">'
				for (var i = 0; i < inlay[type].MainColor.length; i++) {
					color += '<option value="'+inlay[type].MainColor[i][0]+'">'+ _(inlay[type].MainColor[i][1]) +'</option>'
				}
				color+='</select></div>';
				$("#data_shape_box").after(color);
				//证书
				var cert=['<div class="form_control data_cert"><label>'+_("成品证书")+'：</label><input type="text" placeholder="'+_("成品证书")+'" name="CertType"/></div>',
						'<div class="form_control data_cert"><label>'+_("主石证书")+'：</label><input type="text" placeholder="'+_("主石证书")+'" name="MainCertType"/></div>',
				'<div class="form_control data_cert"><label>'+_("证书号码")+'：</label><input type="text" placeholder="'+_("证书号码")+'" name="MainCertNo"/></div>'].join('');
				$("#data_material_box").after(cert);			
				if(type==2 || type==3){
					var clarity='<div class="form_control" id="data_clarity"><label><b class="no_null">*</b>'+_("净度")+'：</label><select name="MainClarity">';
					for(var i=0;i<inlay[type].MainClarity.length;i++){
						clarity+='<option value="'+inlay[type].MainClarity[i][0]+'">'+_(inlay[type].MainClarity[i][1])+'</option>'
					}
					clarity+='</select></div>';
					$("#data_color").after(clarity);
				}
				if(type>3){
					//产地
					var place='<div class="form_control" id="data_place"><label><b class="no_null">*</b>'+_("产地")+'：</label><select name="Place">'
					for (var i = 0; i < inlay[type].Place.length; i++) {
						place += '<option value="'+inlay[type].Place[i][0]+'">'+ _(inlay[type].Place[i][1]) +'</option>'
					}
					place+='</select></div>';
					$("#data_color").after(place);
					if(type==4 || type==5){
						//处理
						var process='<div class="form_control" id="data_process"><label><b class="no_null">*</b>'+_("处理")+'：</label><select name="Process">'
						for (var i = 0; i < inlay[type].Process.length; i++) {
							process += '<option value="'+inlay[type].Process[i][0]+'">'+ _(inlay[type].Process[i][1]) +'</option>'
						}
						process+='</select></div>';
						$("#data_color").after(process);
					}
				}
			}

		},
	}
	addForm.init();
})();
